// 引入 用来发送请求的方法，路径要补全
var util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 商品分类列表
    categoryList:[],
    // 商品分类ID列表
    categoryIdList:[],
    // 标记选中的商品分类id
    currCategoryId:0,
    // 商品分类
    currCategory: '请选择',
    // 选好的商品图片临时路径
    imgList:[],
    // 返回服务器图片的存放位置
    imgPathList:[],
    // 已经保存到数据库中商品的 id
    commodityId:0,
    // 是否显示添加图片按钮（最多添加五张图片）
    showChooseView:true,
    index:0,
    // 选择的分类
    catIndex: -1,
    // 选择的品质
    quaIndex: -1,
    address: '',
    // 地址
    location: {
      latitude: 0.0, 
      longitude: 0.0
    },
    quality: ['全新', "几乎全新", '轻微使用', '明显使用']
  },

  // 选择分类
  selectCategoryHandle: function(e){
    let idx = e.detail.value;
    let currCategoryId = this.data.categoryIdList[idx];
    console.log('获取分类', idx, currCategoryId);
    this.setData({
      catIndex: idx,
      currCategoryId
    });
  },

  selectQualityHandle: function(e){
    let idx  = e.detail.value;
    this.setData({
      quaIndex: idx
    });
  },

  // 获取当前地理位置
  getLocationHandle: function(e){
    let _self = this;
    wx.authorize({
      scope: "scope.userLocation",
      success: function(){
        wx.chooseLocation({
          success: function(data){
            console.log('获取的地理位置', data);
            _self.setData({
              address: data.address,
              location: data
            });
          }
        })
      },
      fail: function(){
        wx.showToast({
          title: '获取位置授权失败',
          icon: "none"
        })
      }
    })
  },

  // 选择商品分类(picker列表中，无法将商品分类与其Id绑定在一起,另需要一个 currCategoryId 标记选中的 分类id)
  bindCategoryPickerChange: function(e){
    let id = e.detail.value;
    let currCategoryId = this.data.categoryIdList[id];
    this.setData({
      index: id,
      currCategoryId
    });
  },
  // 获取商品分类列表、商品分类ID列表（picker列表中，无法将商品分类与其Id绑定在一起）
  getCategoryList(){
    var that = this;
    wx.request({
      url: util.BASE_URL + "category/getAllCategory",
      method: 'GET',
      success:function(result){
        let categoryDataList = result.data;
        let categoryList = [];
        let categoryIdList = [];
        for(let i = 1; i < categoryDataList.length;i++){
          categoryList.push(categoryDataList[i].cateName);
          categoryIdList.push(categoryDataList[i].id);
        }
        that.setData({
          categoryList,
          categoryIdList
        })
      }
    })
  },
  // 选择图片
  handleChooseImg:function(){
    var that = this;
    // 最多选择5张图片
    if(this.data.imgList.length < 5){
      wx.chooseImage({
        count: 5,
        sizeType:['compressed'],
        sourceType:['album','camera'],
        success(res){
          let tempFilePaths = res.tempFilePaths;
          console.log(tempFilePaths);
          if(tempFilePaths.length == 0){
            return;
          }
          let imgArrNow = that.data.imgList;
          imgArrNow = imgArrNow.concat(tempFilePaths);
          if(imgArrNow.length > 5){
            wx.showToast({
              title: '最多可选择5张图片',
              icon: 'none',
              duration: 2000
            })
            return;
          }
          that.setData({
            imgList:imgArrNow
          });
          that.handleShowChooseView();
        }
      })
    } else{
      wx.showToast({
        title: '最多可选择5张图片',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 删除选中图片事件
  handleDeleteImg:function(e){
    let index = e.currentTarget.dataset.id;
    let imgList = this.data.imgList;
    imgList.splice(index,1);
    this.setData({
      imgList
    });
    this.handleShowChooseView();
  },
  // 是否显示添加图片按钮框
  handleShowChooseView:function(){
    let imgListCount = this.data.imgList.length;
    if(imgListCount >= 5){
      this.setData({
        showChooseView:false
      });
    } else{
      this.setData({
        showChooseView:true
      });
    }
  },
  // 预览图片
  handleShowBigImg:function(e){
    let index = e.currentTarget.dataset.id;
    let imgList = this.data.imgList;
    wx.previewImage({
      urls: imgList,
      current: imgList[index]
    })
  },

  cancelHandle: function(){
    wx.showModal({
      content: '您确定要退出吗',
      cancelColor: '#333333',
      confirmColor: '#477FF7',
      success: function(res){
        if(res.confirm){
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    });
  },


  // 绑定事件
  inputContentHandle: function(e){
     console.log('绑定输入事件', e);
  },

  // 提交表单（校验表单、上传数据、上传图片）
  handleSubmitForm: function(e){
    let that = this;
    let data = e.detail.value;
    let categoryId = this.data.currCategoryId;
    let {title} = data;
    let {price} = data;
    let {oldPrice} = data;
    let {quality} = data;
    let {repertory} = data;
    let {description} = data;  
    let {address} = data;
    let userId = wx.getStorageSync('userInfo').id;
    // 校验表单
    if(title == ''){
      this.verifyForm("标题");
      return;
    }
    if(categoryId == 0){
      this.verifyForm("商品分类");
      return;
    }
    if(this.data.imgList.length == 0){
      this.verifyForm("商品图片");
      return;
    }
    if(price == ''){
      this.verifyForm("价格");
      return;
    }
    if(oldPrice == ''){
      this.verifyForm("原价");
      return;
    }
    if(repertory == ''){
      this.verifyForm("商品数量");
      return;
    }
    if(quality == ''){
      this.verifyForm("品质");
      return;
    }
    if(description == ''){
      this.verifyForm("商品描述");
      return;
    }
    // 提交商品信息
    this.uploadData(data).then(
      resolve=>{
        // 提交商品图片
        let commodityId = this.data.commodityId;
        if(commodityId == 0){
          wx.showToast({
            title: '商品信息上传失败！',
            icon:'none',
            duration:2000
          })
          return;
        }
        let imgList = that.data.imgList;
        util.uploadFileToOss(`commodity`, imgList, function(pathList){
            wx.request({
              url: `${util.BASE_URL}commodity/images`,
              method: 'POST',
              data: {
                id: commodityId,
                imageList: pathList
              },
              success: function(res){
                wx.showToast({
                  title: '图片上传成功',
                  icon: 'none',
                  duration: 2000
                })
              },
              fail: function(){
                wx.showToast({
                  title: '图片上传失败',
                  icon: 'none',
                  duration: 2000
                })
              }
            })
        });
        util.success(function(){
          wx.navigateBack({
            detail: 1
          })
        });
      },
      reject=>{
        wx.showToast({
          title: '商品上传失败！请联系管理员',
          icon:'none',
          duration:2000
        })
      }
    );

  },

  // 提交表单数据
  uploadData:function(data){
    var that = this;
    let categoryId = this.data.currCategoryId;
    let address = this.data.address || '';
    let {latitude, longitude, name} = this.data.location;
    let {title} = data;
    let {price} = data;
    let {oldPrice} = data;
    let {quality} = data;
    let {repertory} = data;
    let {description} = data; 
    let userId = wx.getStorageSync('userInfo').id;
    return new Promise((resolve,reject)=>{
      wx.request({
        url: util.BASE_URL + "commodity/uploadData",
        method: 'POST',    
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        }, 
        data:{
          userId,
          title,
          categoryId,
          price,
          oldPrice,
          quality, 
          repertory: 1, 
          description,
          address,
          latitude,
          longitude,
          addrName: name || ''
        },
        success:function(res){
        console.log(res);
          if(res.data.success){
            that.setData({
              commodityId:res.data.commodityId
            });
            resolve(res);
          } else{
            reject(res);
          }
        },
        fail:function(err){
          reject(err);
        }
      })
    });
  },
  // 校验表单，并给出提示信息
  verifyForm:function(content){
      wx.showToast({
        title: content +　'不能为空！',
        icon: 'none',
        duration:2000
      })
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取商品分类列表
    this.getCategoryList();
    // this.getLocationHandle();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})